package com.withouther.robot.rainingrobot.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyuncs.exceptions.ClientException;
import com.withouther.robot.rainingrobot.core.constants.AsrType;
import com.withouther.robot.rainingrobot.core.constants.RoleType;
import com.withouther.robot.rainingrobot.model.AccessToken;
import com.withouther.robot.rainingrobot.service.RobotRecordService;
import com.withouther.robot.rainingrobot.util.WebScoketUtils;
import com.withouther.robot.rainingrobot.util.ai.dialogue.RobotFactory;
import com.withouther.robot.rainingrobot.util.ai.dialogue.model.BotResult;
import com.withouther.robot.rainingrobot.util.ai.tts.TTSAudioFactory;
import com.withouther.robot.rainingrobot.util.ai.tts.model.TTSParam;
import com.withouther.robot.rainingrobot.util.ai.tts.model.TTSResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName RobotRecordServiceImpl
 * @Auther: tzq
 * @Date: 2020/9/21 15:08
 * @Description:
 */
@Service
@Slf4j
public class RobotRecordServiceImpl implements RobotRecordService {


    @Override
    public BotResult getDialogue(String text) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("text", text);
        BotResult botResult = null;
        try {
            botResult = RobotFactory.getFactory().botAction(paramMap, AsrType.ALI);
            log.info("Find the next flow as:{}", botResult.getMessage());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        if (StrUtil.isEmpty(botResult.getText())) {
            log.error("No answer found：{}", botResult);
            botResult.setText("哎呀，你想问的问题，人家暂时不会呢。");
            botResult.setSuccess(false);
        }
        return botResult;
    }

    @Override
    public Map<String, Object> initAuth(AccessToken accessToken) throws Exception {
        // 暂时不验证Token
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("text", "Hi");
        BotResult botResult = RobotFactory.getFactory().botAction(paramMap, AsrType.ALI);

        String channelId = IdUtil.objectId();
        int roleType = RoleType.SERVICE;
        String keyId = WebScoketUtils.getScoketKey(channelId, roleType);
        WebScoketUtils.intentSwitchMap.put(keyId, "on");
        TTSParam ttsParam = new TTSParam();
        ttsParam.setText(botResult.getText());
        TTSResult ttsResult = TTSAudioFactory.getFactory().ttsAction(ttsParam, AsrType.ALI);
        WebScoketUtils.userMap.put(keyId, ttsResult.getFilePath());
        paramMap.put("channelId", channelId);
        paramMap.put("roleType", roleType);
        return paramMap;
    }
}
